package main

import (
	"crypto"
	_ "crypto/md5"
	"encoding/base64"
	"encoding/hex"
	"fmt"
	_ "io"
	"log"
	"strconv"
	"time"

	"github.com/zc2638/go-standard/src/crypto/aes/extra"
)

// 实现AES加密算法
func main() {

	    //创建一个周期性的定时器
		ticker := time.NewTicker(10 * time.Second)
		fmt.Println("AES-CBC-128 用户登录加密校验工具")
	
		go func() {
			for {
				<-ticker.C
				CBC()
	
			}
		}()
	
		for {
			time.Sleep(time.Second * 5)
		}
}

func CBC() {

	tec := time.Now().Unix() 
	t100 :=(tec/100)*100
	fmt.Println("要加密的账户: admin")
	fmt.Println("当前时间戳: ", tec)
	fmt.Println("精度向下取整: ", t100)

	hash := crypto.MD5
	h2 := hash.New()

	str_t100 := strconv.FormatInt(t100,10)

	h2.Write([]byte(str_t100))
	m2 := h2.Sum(nil)
	fmt.Printf("MD5(%v) 时间戳: %x \r\n",t100,m2)
	fmt.Printf("AES-CBC-128 KEY: %x \r\n",m2[0:8])
	fmt.Printf("AES-CBC-128  IV: %x \r\n",m2[8:])

	//str_t100 :=hex.EncodeToString(m2[0:8])
	
	// 声明一个16字节的key
	var key =  []byte(hex.EncodeToString(m2[0:8]))
	// 声明一个随意长度的 需加密内容
	var origin = []byte("admin")
	// 声明一个16字节的iv
	var iv = []byte(hex.EncodeToString(m2[8:]))

	// 加密
	cipherText, err := extra.CBCEncrypt(origin, key, iv)
	if err != nil {
		log.Fatal(err)
	}

	// byte转base64字符串
	cipherTextStr := base64.StdEncoding.EncodeToString(cipherText)
	fmt.Println("AES-CBC-128 加密内容: ", cipherTextStr)

	// 解密
	originText, err := extra.CBCDecrypt(cipherText, key, iv)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("AES-CBC-128 解密内容: ", string(originText))
	fmt.Println("----------------------------------------------------- ")
}